//
//  ZMClient.m
//  ZMUnderFrameWorkDemo
//
//  Created by chenzm on 2020/4/29.
//  Copyright © 2020 MAC. All rights reserved.
//

#import "ZMClient.h"
#import "ZMWkwebViewVC.h"


@implementation ZMClient

+(void)postWithUrl:(NSString*)url
            params:(NSMutableDictionary*)params
     isShowLoading:(BOOL)isLoading
            showVC:(UIViewController*)vc
       promptStyle:(PromptStyle)style
         sureBlock:(void (^)(NSDictionary*dic,NSString *msg))block
       noDataBlock:(void (^)(NSDictionary*noDic,NSString *msg))noBlock
           failure:(void (^)(NSError *error,NSString *msg))fail{
    if (isLoading) {
        [MBProgressHUD jj_showTitle:nil view:kWindow];
    }
    NSURLSessionDataTask *task = [[ZMClient share] zm_postUrl:url params:params success:^(NSDictionary * _Nonnull response) {
        [[ZMClient share].requestMarr removeObject:task];
        if (isLoading) {
            [MBProgressHUD jj_dismiss:kWindow];
        }
        NSString *content=response[@"msg"];
        if (kIsResResult(response)) {
            block(response,kIsEmptyStr(content)?@"":content);
        }else{
            NSString *code=response[@"status"];
            NSString *errStr = [NSString stringWithFormat:@"%@:%@",content,code];
            [self otherStatusPromptStyle:style response:response viewController:vc block:^{
                noBlock(response,kIsEmptyStr(errStr)?@"":errStr);
            }];
        }
    } failure:^(NSError * _Nonnull error) {
        [[ZMClient share].requestMarr removeObject:task];
        if (isLoading) {
            [MBProgressHUD jj_dismiss:kWindow];
        }
        [self failPromptStyle:style viewController:vc responseObject:error failureBlock:^{
            !fail?:fail(error,error.userInfo[NSLocalizedDescriptionKey]);
        }];
    }];
}

+(void)getWithUrl:(NSString*)url
            params:(NSMutableDictionary*)params
     isShowLoading:(BOOL)isLoading
            showVC:(UIViewController*)vc
       promptStyle:(PromptStyle)style
         sureBlock:(void (^)(NSDictionary*dic,NSString *msg))block
       noDataBlock:(void (^)(NSDictionary*noDic,NSString *msg))noBlock
           failure:(void (^)(NSError *error,NSString *msg))fail{
    if (isLoading) {
        [MBProgressHUD jj_showTitle:nil view:kWindow];
    }
    NSURLSessionDataTask *task = [[ZMClient share] zm_getUrl:url params:params success:^(NSDictionary * _Nonnull response) {
        [[ZMClient share].requestMarr removeObject:task];
        if (isLoading) {
            [MBProgressHUD jj_dismiss:kWindow];
        }
        NSString *content=response[@"msg"];
        
        if (kIsResResult(response)) {
            block(response,kIsEmptyStr(content)?@"":content);
        }else{
            NSString *code=response[@"status"];
            NSString *errStr = [NSString stringWithFormat:@"%@:%@",content,code];
            [self otherStatusPromptStyle:style response:response viewController:vc block:^{
                noBlock(response,kIsEmptyStr(errStr)?@"":errStr);
            }];
        }
    } failure:^(NSError * _Nonnull error) {
        [[ZMClient share].requestMarr removeObject:task];
        if (isLoading) {
            [MBProgressHUD jj_dismiss:kWindow];
        }
        [self failPromptStyle:style viewController:vc responseObject:error failureBlock:^{
            !fail?:fail(error,error.userInfo[NSLocalizedDescriptionKey]);
        }];
    }];
    [[ZMClient share].requestMarr addObject:task];
}


#pragma mark - Methods
/// 取消｜移除所有请求
+(void)zm_removeAllRequest{
    [[ZMClient share].requestMarr removeAllObjects];
}

/// 监听网络状态
+(void)zm_monitorNetworkStatus{
    //网络变化
    [[ZMClient share].manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case -1:{
                ZMLog(@"当前网络状态改变为:%ld    未知网络",(long)status);
            }break;
            case 0:{
                ZMLog(@"当前网络状态改变为:%ld    没有网络",(long)status);
                [MBProgressHUD jj_showDelayTitle:@"网络不给力,稍后再试"];
            }break;
            case 1:{
                ZMLog(@"当前网络状态改变为:%ld    窝蜂网络",(long)status);
            }break;
            case 2:{
                ZMLog(@"当前网络状态改变为:%ld    WiFi网络",(long)status);
            }break;
            default:
                break;
        }
    }];
    
    [[ZMClient share].manager.reachabilityManager startMonitoring];
}




/// 获取图片信息（阿里云图片）
+(void)getImgInfo:(NSString*)url
            params:(NSMutableDictionary*)params
     isShowLoading:(BOOL)isLoading
            showVC:(UIViewController*)vc
       promptStyle:(PromptStyle)style
         sureBlock:(void (^)(NSDictionary*dic,NSString *msg))block
       noDataBlock:(void (^)(NSDictionary*noDic,NSString *msg))noBlock
           failure:(void (^)(NSError *error,NSString *msg))fail{
    if (isLoading) {
        [MBProgressHUD jj_showTitle:nil view:kWindow];
    }
    NSURLSessionDataTask *task = [[ZMClient share] zm_getUrl:[NSString stringWithFormat:@"%@?x-oss-process=image/info",url] params:params success:^(NSDictionary * _Nonnull response) {
        [[ZMClient share].requestMarr removeObject:task];
        if (isLoading) {
            [MBProgressHUD jj_dismiss:kWindow];
        }
        NSString *content=response[@"msg"];
        if (kIsResResult(response)) {
            block(response,kIsEmptyStr(content)?@"":content);
        }else{
            noBlock(response,kIsEmptyStr(content)?@"":content);
        }
    } failure:^(NSError * _Nonnull error) {
        [[ZMClient share].requestMarr removeObject:task];
        if (isLoading) {
            [MBProgressHUD jj_dismiss:kWindow];
        }
        !fail?:fail(error,error.userInfo[NSLocalizedDescriptionKey]);
    }];
    [[ZMClient share].requestMarr addObject:task];
}


+(void)updateFileWithUrl:(NSString*)url
                fileType:(NSInteger)fileType
                filesArr:(NSArray *)filesArr
                  params:(NSMutableDictionary*)params
                 maxByte:(NSInteger)maxByte// 最大上传质量 单位kB 0、默认原件上传
           isShowLoading:(BOOL)isLoading
               toastFail:(BOOL)isToast
               sureBlock:(void (^)(NSDictionary*dic,NSString *msg))block
             noDataBlock:(void (^)(NSDictionary*noDic,NSString *msg))noBlock
                 failure:(void (^)(NSError *error,NSString *msg))fail{
    if (isLoading) {
        [MBProgressHUD jj_showTitle:nil view:kWindow];
    }
    NSURLSessionDataTask *task = [[ZMClient share] zm_uploadFileUrl:url fileType:fileType filesArr:filesArr params:params maxByte:maxByte success:^(NSDictionary * _Nonnull response) {
        [[ZMClient share].requestMarr removeObject:task];
        if (isLoading) {
            [MBProgressHUD jj_dismiss:kWindow];
        }
        NSString *content=response[@"msg"];
        if (kIsResResult(response)) {
            block(response,kIsEmptyStr(content)?@"":content);
        }else{
            if (isToast) {
                [MBProgressHUD jj_showDelayTitle:kIsEmptyStr(content)?@"请求错误":content view:kWindow];
            }
            noBlock(response,kIsEmptyStr(content)?@"":content);
        }
    } failure:^(NSError * _Nonnull error) {
        [[ZMClient share].requestMarr removeObject:task];
        if (isLoading) {
            [MBProgressHUD jj_dismiss:kWindow];
        }
        if (isToast) {
            NSData *data= error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
            NSDictionary *object = @{};
            if (data) {
                object = [self jsonToDic:data];
            }
            // 错误信息
            NSString * content = object[@"msg"];
            if (!content.length) {
                content=[self getCodeString:error];
            }
            [MBProgressHUD jj_showDelayTitle:kIsEmptyStr(content)?@"请求错误":content view:kWindow];
        }
        !fail?:fail(error,error.userInfo[NSLocalizedDescriptionKey]);
    }];
    [[ZMClient share].requestMarr addObject:task];
}


#pragma mark - 逻辑处理
/// AF返回成功处理
static BOOL isAlert = YES;// 设置避免多次弹窗
+(void)otherStatusPromptStyle:(PromptStyle)style
        response:(NSDictionary *)response
        viewController:(UIViewController*)vc block:(void (^)(void))block{
    NSString *content=response[@"msg"];
    NSInteger code = [response[@"status"] integerValue];
    //解析成功
    if (kIsResResult(response)) {
    }else{
        if (code >= 9000) {
            //9000:token过期  9001：token格式不正确 9002:账号在其他地方登录
            if (isAlert) {
                isAlert = NO;
                if (code == 9002) {
                    [NSObject alertViewWithTitle:nil contentText:@"你的账号已在其他地方登录" leftButtonTitle:@"确定" rightButtonTitle:nil finish:^(NSInteger index) {
                        isAlert = YES;

                        [kAppDelegate initRootWithType:0 vc:vc];
                    }];
                }else{
                    isAlert = YES;
                    [kAppDelegate initRootWithType:0 vc:vc];
                }
            }
        }else{
            !block?:block();
            
            [self openHtmlError:[response mj_JSONString] target:vc];
            
            if (style==PStyleNone) {
            }
            if (style==PStyleSystem) {
                [NSObject alertViewWithTitle:content contentText:nil leftButtonTitle:@"确定" rightButtonTitle:nil finish:^(NSInteger index) {
                }];
            }
            if (style==PStyleMBProgress ) {
                [MBProgressHUD jj_showDelayTitle:content view:kWindow];
            }
            if (style==PStylePrompt) {
                [QuickPrompt showAtTop:content];
            }
        }
    }
}

/// AF返回失败处理
+(void)failPromptStyle:(PromptStyle)style//提示的样式
        viewController:(UIViewController*)vc
        responseObject:(NSError*)error//得到的失败的error
          failureBlock:(void (^)(void))block{//失败回调
    if (error.code!=NSURLErrorCancelled) {
        [ZMClient openHtmlError:[self getErrorDataByStr:error] target:vc];
        NSData *data= error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
        NSDictionary *object = @{};
        if (data) {
            object = [self jsonToDic:data];
        }
        // 错误信息
        NSString * content = object[@"msg"];
        if (!content.length) {
            content=[self getCodeString:error];
        }
        
        
        if (kJudgeCode(object, 401)) {
            [NSObject alertViewWithTitle:content contentText:nil leftButtonTitle:@"确定" rightButtonTitle:nil finish:^(NSInteger index) {
                if (index == 0) {
                    /// 重新登录？
                }
            }];
        } else if (kJudgeCode(object,429)) {
            [MBProgressHUD jj_showDelayTitle:@"请求过于频繁，请稍后再试！" view:kWindow];
            if (block) {
                block();
            }
        } else {
            if (block) {
                block();
            }
            if (style==PStyleNone) {
            }
            if (style==PStyleSystem) {
                [NSObject alertViewWithTitle:content contentText:nil leftButtonTitle:@"确定" rightButtonTitle:nil finish:^(NSInteger index) {
                }];
            }
            if (style==PStyleMBProgress ) {
                [MBProgressHUD jj_showDelayTitle:content view:kWindow];
            }
            if (style==PStylePrompt) {
                [QuickPrompt showAtTop:content];
            }
        }
    }else{
        
    }
}


///打印错误信息
+ (void)openHtmlError:(NSString *)str target:(UIViewController *)target{
#ifdef FMURL_Debug
    if (!str||str.length == 0) {
        return;
    }
    return;
    ZMWkwebViewVC *vc = [ZMWkwebViewVC new];
    [vc.wkWebView loadHTMLString:str baseURL:kURL(@"www://baidu.com")];
    vc.hidesBottomBarWhenPushed = YES;
    vc.title = @"错误详情";
    if (target) {
        [target.navigationController pushViewController:vc animated:YES];
    }
#endif
}



+(NSString *)getErrorDataByStr:(NSError *)error{
    NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
    NSString *str = [[NSString alloc] initWithData:errorData encoding:NSUTF8StringEncoding];
    return !str?@"":str;
}


+(NSString *)getCodeString:(NSError *)error{
    NSString *content=[[error userInfo]objectForKey:@"NSLocalizedDescription"];
    if (error) {
        switch (error.code) {
            case -1001:{
                content = @"网络请求超时，请检查网络设置！";
            }
                break;
            case -1003:
            case -1004:
            case -1011:{//没有网络
                content = @"服务器无法连接！";
            }
                break;
            case -1009:
            {//没有网络
                content = @"当前网络断啦，请检查网络设置！";
            }
                break;
            case -999:{//没有网络
                content = @"当前网络断啦，请检查网络设置！";
            }
                break;
            default:
                break;
        }
        
    }
    return content;
}

#pragma mark- Lazyload
-(NSMutableArray *)requestMarr{
    if (!_requestMarr) {
        _requestMarr = [NSMutableArray new];
    }
    return _requestMarr;
}



@end
